package com.chookss.video;

import android.content.Context;
import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.aliyun.apsara.alivclittlevideo.R;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.OnTimeExpiredErrorListener;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.PagerLayoutManager;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.RecyclerViewEmptySupport;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.VideoQuality;
import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.bean.ErrorCode;
import com.aliyun.player.bean.ErrorInfo;
import com.aliyun.player.bean.InfoBean;
import com.aliyun.player.bean.InfoCode;
import com.aliyun.player.nativeclass.CacheConfig;
import com.aliyun.player.nativeclass.MediaInfo;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.aliyun.player.nativeclass.TrackInfo;
import com.aliyun.player.source.StsInfo;
import com.aliyun.player.source.VidAuth;
import com.aliyun.svideo.common.utils.ToastUtils;
import com.chookss.MyApp;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.video.entity.VideoEntity;
import com.chookss.video.model.GetPlayAuthImpl;
import com.chookss.video.model.IGetPlayAuth;
import com.chookss.video.model.IVideoSourceModel;
import com.chookss.video.model.VideoPlayCountRecorder;
import com.cicada.player.utils.Logger;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 视频列表view
 *
 * @author xlx
 */
public class AlivcVideoListsSmallView extends FrameLayout {
    private static String TAG = AlivcVideoListsSmallView.class.getSimpleName();
    private Context mContext;
    private RecyclerViewEmptySupport recycler;
    private SwipeRefreshLayout refreshView;
    private BaseVideoListAdapter adapter;
    private PagerLayoutManager pagerLayoutManager;
    private IGetPlayAuth getPlayAuth = new GetPlayAuthImpl();

    private View mPlayerViewContainer;
    /**
     * 数据是否到达最后一页
     */
    private boolean isEnd;
    /**
     * 播放器的封装，可以提前准备视频
     */
    private AliPlayer mListPlayer;
    private TextureView mTextureView;
    private List<IVideoSourceModel> list;

    /**
     * 刷新数据listener
     */
    private OnRefreshDataListener onRefreshDataListener;
    /**
     * 判断是否处于加载数据的状态中
     */
    private boolean isLoadingData;
    /**
     * 预加载位置, 默认离底部还有5条数据时请求下一页视频列表
     */
    private static final int DEFAULT_PRELOAD_NUMBER = 5;
    /**
     * 是否点击暂停
     */
    private boolean isPause = false;
    /**
     * 当前页面是否处于可见状态
     */
    private boolean isOnBackground = true;
    /**
     * 当前选中位置
     */
    private int mCurrentPosition;
    /**
     * 正常滑动，上一个被暂停的位置
     */
    private int mLastStopPosition = -1;
    private RecyclerView.RecycledViewPool mRecycledViewPool;
    private ImageView mPlayIcon;
    private long playTimeInMills = 0;//当前播放时长
    private long playTimeCurrent = 0;//当前播放进行中的时长
    private long playTimeCurrentAll = 0;//当前播放累计时长
    private String authId = "";//计费所用
    private String type = "0";//0暂无内容1暂无关注
    private View ll_empty;
    private VideoEntity currentVideoEntity = null;

    public AlivcVideoListsSmallView(@NonNull Context context) {
        super(context);
        this.mContext = context;
        initPlayer();
        init();
    }

    private AlivcVideoListsSmallView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        throw new IllegalArgumentException("this view isn't allow create by xml");
    }

    private GestureDetector gestureDetector;

    /**
     * 初始化播放器相关
     */
    private void initPlayer() {
        mPlayerViewContainer = View.inflate(getContext(), R.layout.layout_player_view, null);
        mTextureView = mPlayerViewContainer.findViewById(R.id.video_textureview);
        gestureDetector = new GestureDetector(mContext,
                new GestureDetector.SimpleOnGestureListener() {

                    @Override
                    public boolean onSingleTapConfirmed(MotionEvent e) {
                        //判断当前view是否可见，防止退后台、切换页面和单击同时操作导致，退后台时视频又重新开始播放
                        if (AlivcVideoListsSmallView.this.isShown()) {
                            onPauseClick();
                        }
                        return true;
                    }

                    @Override
                    public boolean onDown(MotionEvent e) {
                        return true;
                    }
                });
        mPlayerViewContainer.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                Surface mSurface = new Surface(surface);
                if (mListPlayer != null) {
                    mListPlayer.setSurface(mSurface);
                    mListPlayer.redraw();
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                if (mListPlayer != null) {
                    mListPlayer.redraw();
                }
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                if (mListPlayer != null) {
                    mListPlayer.setSurface(null);
                }
                return true;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });
        mListPlayer = AliPlayerFactory.createAliPlayer(mContext);
        //打开播放器
        //开启硬解
        mListPlayer.enableHardwareDecoder(true);
//        mListPlayer.setPreloadCount(7);
        PlayerConfig config = mListPlayer.getConfig();
        config.mClearFrameWhenStop = true;
        config.mStartBufferDuration = 100;
        mListPlayer.setConfig(config);
        CacheConfig cacheConfig = new CacheConfig();
        //开启缓存功能
        cacheConfig.mEnable = true;
        //能够缓存的单个文件最大时长。超过此长度则不缓存
        cacheConfig.mMaxDurationS = 300;
        //缓存目录的位置
        cacheConfig.mDir = mContext.getExternalCacheDir().getAbsolutePath();
        //缓存目录的最大大小。超过此大小，将会删除最旧的缓存文件
        cacheConfig.mMaxSizeMB = 2048;
        //设置缓存配置给到播放器
        mListPlayer.setCacheConfig(cacheConfig);
        mListPlayer.setLoop(true);
        mListPlayer.setAutoPlay(true);
        //mListPlayer.set
        //指定播放清晰度
//        mListPlayer.setDefinition(VideoQuality.PLAY.getValue());
        mListPlayer.setOnInfoListener(new IPlayer.OnInfoListener() {
            @Override
            public void onInfo(InfoBean ib) {
                if (ib.getCode() == InfoCode.CurrentPosition) {
                    if (ib.getExtraValue() > playTimeCurrent) {
                        playTimeCurrent = ib.getExtraValue();
                    } else {
                        playTimeCurrentAll = playTimeCurrentAll + playTimeCurrent;
                        playTimeCurrent = 0;
                    }
                    playTimeInMills = playTimeCurrent + playTimeCurrentAll;
                }
            }
        });
        mListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
            @Override
            public void onPrepared() {
                MediaInfo mediaInfo = mListPlayer.getMediaInfo();
                List<TrackInfo> trackInfos = mediaInfo.getTrackInfos();
                int size = trackInfos.size();
                for (TrackInfo trackInfo : trackInfos) {
                    if (trackInfo.getVodDefinition().equals(VideoQuality.PLAY.getValue())) {
                        float aspectRatio = (float) trackInfo.getVideoWidth() / trackInfo.getVideoHeight();
                        if (aspectRatio < 9f / 15f) {
                            mListPlayer.setScaleMode(IPlayer.ScaleMode.SCALE_ASPECT_FILL);
                        } else {
                            mListPlayer.setScaleMode(IPlayer.ScaleMode.SCALE_ASPECT_FIT);
                        }
                        break;
                    }
                }
                if (!isPause && !isOnBackground) {
                    if (mListPlayer != null) {
                        mListPlayer.start();
                    }
                }
            }

        });

        mListPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
            @Override
            public void onRenderingStart() {
                //  2018/11/21 隐藏封面
                BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(mCurrentPosition);
                if (holder != null) {
                    holder.getCoverView().setVisibility(GONE);
                }
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingEnd();
                }
            }
        });

        mListPlayer.setOnLoadingStatusListener(new IPlayer.OnLoadingStatusListener() {
            @Override
            public void onLoadingBegin() {
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingBegin();
                    KLog.i("-------onLoadingBegin");
                }
            }

            @Override
            public void onLoadingEnd() {
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingEnd();
                    KLog.i("-------onLoadingEnd");
                }
            }

            @Override
            public void onLoadingProgress(int percent,
                                          float netSpeed) {
                if (mLoadingListener != null) {
                    mLoadingListener.onLoadingProgress(percent, netSpeed);
                }
            }
        });
        mListPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
            @Override
            public void onError(ErrorInfo errorInfo) {
                if (errorInfo.getCode() == ErrorCode.ERROR_SERVER_POP_TOKEN_EXPIRED) {
                    //鉴权过期
                    if (mTimeExpiredErrorListener != null) {
                        mTimeExpiredErrorListener.onTimeExpiredError();
                        Log.i(TAG, "刷新鉴权");
                    }
                }
                ToastUtils.show(getContext(), errorInfo.getMsg());
            }
        });
//        enableNativeLog();
    }

    /**
     * 开启底层日志
     */
    public void enableNativeLog() {
        Logger.getInstance(getContext()).enableConsoleLog(true);
        Logger.getInstance(getContext()).setLogLevel(Logger.LogLevel.AF_LOG_LEVEL_TRACE);
    }

    /**
     * 鉴权过期时发生
     */
    private OnTimeExpiredErrorListener mTimeExpiredErrorListener;

    public void setTimeExpiredErrorListener(
            OnTimeExpiredErrorListener mTimeExpiredErrorListener) {
        this.mTimeExpiredErrorListener = mTimeExpiredErrorListener;
    }

    private LinearLayout ll_empty_view;

    private void init() {
        list = new ArrayList<>();
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_video_list, this, true);
        recycler = view.findViewById(R.id.recycler);
        refreshView = view.findViewById(R.id.refresh_view);
        ll_empty_view = view.findViewById(R.id.ll_empty_view);
        refreshView.setColorSchemeColors(Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED);
        refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (onRefreshDataListener != null) {
                    isLoadingData = true;
                    onRefreshDataListener.onRefresh();
                }
            }
        });
        recycler.setHasFixedSize(true);
        mRecycledViewPool = new RecyclerView.RecycledViewPool();
        mRecycledViewPool.setMaxRecycledViews(0, 50);
        recycler.setRecycledViewPool(mRecycledViewPool);
        pagerLayoutManager = new PagerLayoutManager(mContext);
        pagerLayoutManager.setItemPrefetchEnabled(true);
        recycler.setLayoutManager(pagerLayoutManager);
//        recycler.setEmptyView(view.findViewById(R.id.ll_empty_view));

        pagerLayoutManager.setOnViewPagerListener(new PagerLayoutManager.OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                int position = pagerLayoutManager.findFirstVisibleItemPosition();
                if (position != -1) {
                    mCurrentPosition = position;
                }
                int itemCount = adapter.getItemCount();
                if (itemCount - position < DEFAULT_PRELOAD_NUMBER && !isLoadingData && !isEnd) {
                    // 正在加载中, 防止网络太慢或其他情况造成重复请求列表
                    isLoadingData = true;
                    loadMore();
                }
                startPlay(mCurrentPosition);
                mLastStopPosition = -1;
//                KLog.i("pagerLayoutManager onInitComplete = " + mCurrentPosition);
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {
                if (position >= list.size()) {
                    playTimeInMills = 0;
                    playTimeCurrentAll = 0;
                    playTimeCurrent = 0;
                    stopPlay();
                    return;
                }
//                KLog.i("pagerLayoutManager onPageRelease = " + mCurrentPosition+"=="+position);
                if (mCurrentPosition == position) {
                    IVideoSourceModel video = list.get(mCurrentPosition);
                    if (playTimeInMills > 0) {
                        VideoPlayCountRecorder.Companion.record(video.getVideo().videoId, (int) (playTimeInMills / 1000));
                    }
                    mLastStopPosition = position;
                    playTimeInMills = 0;
                    playTimeCurrentAll = 0;
                    playTimeCurrent = 0;
                    stopPlay();
                    BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(position);
                    if (holder != null) {
                        holder.getCoverView().setVisibility(VISIBLE);
//                        KLog.i("pagerLayoutManager onPageRelease22 = "+position);
                        if (holder.getProgress_bar() != null) {
                            holder.getCompleteTextNumView().setText(Utils.changeNumber(currentVideoEntity.videoSeconds) + "s");
                            holder.getProgress_bar().stop();
                        }
                        if (holder.getPlayIcon() != null) {
                            holder.getPlayIcon().setVisibility(View.GONE);
                        }
                    }
                }

            }

            @Override
            public void onPageSelected(int position, boolean b) {
                //重新选中视频不播放，如果该位置被stop过则会重新播放视频
                if (mCurrentPosition == position && mLastStopPosition != position) {
                    return;
                }
//                KLog.i("pagerLayoutManager onPageSelected = " + mCurrentPosition+"=="+position);
                int itemCount = adapter.getItemCount();
                if (itemCount - position < DEFAULT_PRELOAD_NUMBER && !isLoadingData && !isEnd) {
                    // 正在加载中, 防止网络太慢或其他情况造成重复请求列表
                    isLoadingData = true;
                    loadMore();
                }
                if (itemCount == position + 1 && isEnd) {
                    MyToast.show("已经是最后一个视频了");
                }
                //开始播放选中视频
                startPlay(position);
                mCurrentPosition = position;
            }
        });
    }

    /**
     * 停止视频播放
     */
    private void stopPlay() {
        isPlayingVideo.setVid(null);
        isPlayingVideo.setPlayAuth(null);

        ViewParent parent = mPlayerViewContainer.getParent();
        if (parent != null && parent instanceof FrameLayout) {
            ((FrameLayout) parent).removeView(mPlayerViewContainer);
        }
        if (mListPlayer != null) {
            mListPlayer.stop();
            mListPlayer.setSurface(null);
        }

    }


    private final VidAuth isPlayingVideo = new VidAuth();

    /**
     * 开始播放
     *
     * @param position 播放位置
     */
    private void startPlay(int position) {
        if (position < 0 || position > list.size()) {
            return;
        }
        IVideoSourceModel video = list.get(position);

        //恢复界面状态
        isPause = false;
//        mListPlayer.stop();
//        isPlayingVideo.setPlayAuth(null);
        isPlayingVideo.setVid(video.getVideo().videoId);
        currentVideoEntity = video.getVideo();
        getAuthAndStartPlay(position);
    }

    private void getAuthAndStartPlay(int position) {
        ViewParent parent = mPlayerViewContainer.getParent();
        if (parent != null && parent instanceof FrameLayout) {
            ((ViewGroup) parent).removeView(mPlayerViewContainer);
        }
        BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(position);
        mPlayIcon = holder.getPlayIcon();
        mPlayIcon.setVisibility(View.GONE);
        if (holder != null) {
            holder.getContainerView().addView(mPlayerViewContainer, 0);
        }
        getPlayAuth.call(isPlayingVideo.getVid(), (videoId, playAuth, authId, compeleteFlag) -> {
            if (videoId.equals(isPlayingVideo.getVid()) && !isPause && !isOnBackground) {
                playTimeInMills = 0;
                playTimeCurrentAll = 0;
                playTimeCurrent = 0;
                VidAuth vidAuth = new VidAuth();
                vidAuth.setVid(videoId);
                vidAuth.setPlayAuth(playAuth);
                isPlayingVideo.setPlayAuth(playAuth);
                isPlayingVideo.setVid(videoId);
                currentVideoEntity.compeleteFlag = compeleteFlag;
                if (Utils.isNull(compeleteFlag)) {
                    if (holder != null) {
                        holder.getCompleteRelativeLayout().setVisibility(View.GONE);
                    }
                } else {
                    holder.getCompleteRelativeLayout().setVisibility(View.VISIBLE);
                    if ("1".equals(compeleteFlag)) {
                        if (holder != null) {
                            holder.getCompleteTextNumView().setVisibility(View.GONE);
                            holder.getCompleteTextInitView().setVisibility(View.GONE);
                            holder.getProgress_bar().setVisibility(View.GONE);
                            holder.getCompleteTextView().setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (holder != null) {
                            holder.getCompleteTextView().setVisibility(View.GONE);
                            holder.getProgress_bar().setVisibility(View.VISIBLE);
                            holder.getCompleteTextNumView().setVisibility(View.VISIBLE);
                            holder.getCompleteTextInitView().setVisibility(View.VISIBLE);
                            holder.getCompleteTextView().setSelected(false);
                            holder.getCompleteTextNumView().setText(Utils.changeNumber(currentVideoEntity.videoSeconds) + "s");
                            holder.getCompleteTextInitView().setText("后完成学习");
                            holder.getProgress_bar().setDuration((Utils.changeNumber(currentVideoEntity.videoSeconds)) * 1000);
                            holder.getProgress_bar().start();
                        }
                    }
                }
                //防止退出后台之后，再次调用start方法，导致视频播放
                if (mListPlayer != null) {
                    mListPlayer.setDataSource(vidAuth);
                    mListPlayer.prepare();
                    allTime = 0;
                }
//                mListPlayer.start();
            }
            return null;
        });
    }

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //每分中上传数据
                    if (handler != null) {
                        Message message = new Message();
                        message.what = 1002;
                        handler.sendMessage(message);
                    }
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, 1000, 1000);//执行定时器中的任务
        }
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    private int allTime = -1;
    private int allVedioTime = 1;//视频播放临时时长
    // handler类接收数据
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1002) {
                if (allTime >= 0) {
                    allTime++;
                    if (MyApp.startPlay == 0) {
                        if (allTime == 1) {
                            authId = System.currentTimeMillis() + "-" + new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, "");
                            addVideoCost(isPlayingVideo.getVid(), "0", authId);
                        }
                    } else {
                        if (allTime == MyApp.startPlay + 1) {
                            authId = System.currentTimeMillis() + "-" + new ShareUtils().getString(mContext, StaticClass.EMPLOYEECODE, "");
                            addVideoCost(isPlayingVideo.getVid(), "0", authId);
                        }
                    }
                    if (allTime > 2 && (allTime % MyApp.smalVideoEvery) == 0) {
                        addVideoCost(isPlayingVideo.getVid(), "1", authId);
                    }
                    if (currentVideoEntity != null) {
                        if ("0".equals(currentVideoEntity.compeleteFlag)) {
                            BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(mCurrentPosition);
                            if (holder != null) {
                                if (allTime >= Utils.changeNumber(currentVideoEntity.videoSeconds)) {
                                    holder.getProgress_bar().stop();
                                    holder.getProgress_bar().setVisibility(View.GONE);
                                    holder.getCompleteTextNumView().setVisibility(View.VISIBLE);
                                    holder.getCompleteTextNumView().setText("点击");
                                    holder.getCompleteTextView().setVisibility(View.GONE);
                                    holder.getCompleteTextInitView().setVisibility(View.VISIBLE);
                                    holder.getCompleteTextInitView().setText("学习任务已完成");
                                    currentVideoEntity.compeleteFlag = "1";
                                } else {
                                    if (allTime > 0) {
                                        holder.getCompleteTextNumView().setText((Utils.changeNumber(currentVideoEntity.videoSeconds) - allTime) + "s");
                                    }
                                }
                            }
                        }
                    }

                }
//                KLog.i(allTime+"---------");
            }
        }

    };

    /**
     * 增加播放时长
     */
    private void addVideoCost(String videoId, String playType, String authId) {

        Map<String, String> map = new HashMap<>();
//        （0开始播放或者拖动后 1每XX秒时扣除流量）
        map.put("videoId", videoId);
        map.put("playType", playType);
        map.put("authId", authId);
//        KLog.i(videoId+"----------"+authId);
        if (Utils.isNull(videoId) || Utils.isNull(authId)) {
            return;
        }
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.getVideoCost, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    public void onDestroy() {
        stopTimer();
        if (mListPlayer != null) {
            mListPlayer.stop();
//            mListPlayer.reset();
            mListPlayer.release();
            mListPlayer = null;
        }
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (onRefreshDataListener != null) {
            onRefreshDataListener.onLoadMore();
        }
    }

    public void completeLoadState(boolean isEnd) {
        if (refreshView != null && refreshView.isRefreshing()) {
            refreshView.setRefreshing(false);
            // 加载完毕, 重置加载状态
        }
        this.isEnd = isEnd;
        isLoadingData = false;
    }

    /**
     * 刷新数据
     *
     * @param list 刷新数据
     */
    public void refreshData(List<IVideoSourceModel> list, boolean isEnd) {
        clearNotShowVideo(list);
        if (refreshView != null && refreshView.isRefreshing()) {
            refreshView.setRefreshing(false);
            // 加载完毕, 重置加载状态
        }
        if (mListPlayer != null) {
//            mListPlayer.clear();
//            for (IVideoSourceModel iVideoSourceModel : list) {
//                if (iVideoSourceModel.getSourceType() == VideoSourceType.TYPE_AUTH) {
//                    mListPlayer.addVid(iVideoSourceModel.getVidStsSource().getVid(), iVideoSourceModel.getUUID() );
//                } else if (iVideoSourceModel.getSourceType() == VideoSourceType.TYPE_URL) {
//                    String url = iVideoSourceModel.getUrlSource().getUri();
//                    String uuid = iVideoSourceModel.getUUID();
//                    mListPlayer.addUrl(url, uuid );
//                }
//            }
        }
        this.isEnd = isEnd;
        isLoadingData = false;
        adapter.refreshData(list);
        if (list.size() == 0) {
            ll_empty_view.setVisibility(View.VISIBLE);
            recycler.setEmptyView(ll_empty_view);
        } else {
            ll_empty_view.setVisibility(View.GONE);
            recycler.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 刷新数据，并播放指定位置的视频
     *
     * @param list     视频列表数据
     * @param position 刷新完成之后播放位置
     */
    public void refreshData(List<IVideoSourceModel> list, int position, boolean isEnd) {
        int size = list.size();
        if (position < 0) {
            position = 0;
        }
        if (size <= position) {
            position = size - 1;
        }
        //获取不进行显示
        int notShowVideoCount = 0;

        mCurrentPosition = position - notShowVideoCount;
        refreshData(list, isEnd);
        recycler.scrollToPosition(mCurrentPosition);
        KLog.i("------------------");
    }

    public void scrollToPosition(int position) {
        int size = adapter.getItemCount();
        if (position < 0) {
            position = 0;
        }
        if (size <= position) {
            position = size - 1;
        }
        if (position < 0) {
            return;
        }
        mCurrentPosition = position;
        recycler.scrollToPosition(mCurrentPosition);
    }

    /**
     * 清除不允许显示的视频
     *
     * @param list
     */
    private void clearNotShowVideo(List<IVideoSourceModel> list) {

    }

    /**
     * 加载更多数据
     *
     * @param list
     */
    public void addMoreData(List<IVideoSourceModel> list, final boolean isEnd) {
        if (list == null || list.size() < 1) {
            this.isEnd = isEnd;
        } else {
            this.isEnd = isEnd;
        }
        clearNotShowVideo(list);
        isLoadingData = false;

        if (adapter != null) {
            adapter.addMoreData(list);
            if (adapter.getDataList().size() + list.size() == 0) {
                ll_empty_view.setVisibility(View.VISIBLE);
                recycler.setEmptyView(ll_empty_view);
            } else {
                ll_empty_view.setVisibility(View.GONE);
                recycler.setVisibility(View.VISIBLE);
            }
        }
        if (mListPlayer != null) {
//            for (IVideoSourceModel iVideoSourceModel : list) {
//                if (iVideoSourceModel.getSourceType() == VideoSourceType.TYPE_AUTH) {
//                    mListPlayer.addVid(iVideoSourceModel.getVidStsSource().getVid(), iVideoSourceModel.getUUID() );
//                } else if (iVideoSourceModel.getSourceType() == VideoSourceType.TYPE_URL) {
//                    mListPlayer.addUrl(iVideoSourceModel.getUrlSource().getUri(), iVideoSourceModel.getUUID());
//                }
//            }
        }
        if (refreshView.isRefreshing()) {
            refreshView.setRefreshing(false);
        }
        KLog.i("============");
    }

    private IPlayer.OnLoadingStatusListener mLoadingListener;

    public void setLoadingListener(IPlayer.OnLoadingStatusListener mLoadingListener) {
        this.mLoadingListener = mLoadingListener;
    }

    public void setOnRefreshDataListener(OnRefreshDataListener onRefreshDataListener) {
        this.onRefreshDataListener = onRefreshDataListener;
    }

    /**
     * 刷新数据
     */
    public interface OnRefreshDataListener {
        /**
         * 下拉刷新
         */
        void onRefresh();

        /**
         * 上拉加载
         */
        void onLoadMore();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        if (mRecycledViewPool != null) {
            mRecycledViewPool.clear();
            mRecycledViewPool = null;
        }
        if (mListPlayer != null) {
            mListPlayer.stop();
//            mListPlayer.reset();
            mListPlayer.release();
            mListPlayer = null;
        }
    }

    /**
     * 暂停播放
     */
    private void pausePlay() {
        isPause = true;
        if (mPlayIcon != null) {
            mPlayIcon.setVisibility(View.VISIBLE);
        }
        if (mListPlayer != null) {
            mListPlayer.pause();
        }
    }

    /**
     * 恢复播放
     */
    private void resumePlay() {
        isPause = false;
        if (mPlayIcon != null) {
            mPlayIcon.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(isPlayingVideo.getVid())) {
            return;
        }
        if (TextUtils.isEmpty(isPlayingVideo.getPlayAuth())) {
            getAuthAndStartPlay(mCurrentPosition);
        } else {
            if (mListPlayer != null) {
                mListPlayer.start();
            }
        }
    }

    /**
     * 视频暂停/恢复的时候使用，
     */
    public void onPauseClick() {
        if (isPause) {
            resumePlay();
            resumeProgress();
        } else {
            pausePlay();
            pauseProgress();
        }
    }
    /**
     * activity不可见或者播放页面不可见时调用该方法
     */
    public void setOnBackground(boolean isOnBackground) {
        this.isOnBackground = isOnBackground;
        if (isOnBackground) {
            pausePlay();
            stopTimer();
            pauseProgress();
        } else {
            resumePlay();
            startTimer();
            resumeProgress();
        }
    }

    public void pauseProgress(){
        if (allTime >= 0) {
            allVedioTime = allVedioTime + allTime;
            allTime = -1;
        }
        if (currentVideoEntity != null) {
            if ("0".equals(currentVideoEntity.compeleteFlag)) {
                //任务没有完成
                BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(mCurrentPosition);
                if (holder != null) {
                    holder.getProgress_bar().pause();
                }
            }
        }
    }
    public void resumeProgress(){
        allTime = allTime + 1+allVedioTime;
        allVedioTime = 0;
        if (currentVideoEntity != null) {
            if ("0".equals(currentVideoEntity.compeleteFlag)) {
                //任务没有完成
                BaseVideoListAdapter.BaseHolder holder = (BaseVideoListAdapter.BaseHolder) recycler.findViewHolderForLayoutPosition(mCurrentPosition);
                if (holder != null) {
                    holder.getProgress_bar().resume();
                }
            }
        }
    }
    /**
     * 设置adapter
     *
     * @param adapter
     */
    public void setAdapter(BaseVideoListAdapter adapter) {
        this.adapter = adapter;
        recycler.setAdapter(adapter);
        this.list = adapter.getDataList();
    }

    /**
     * 移除当前播放的视频
     */
    public void removeCurrentPlayVideo() {
        stopPlay();
        int tempCurrentPostion = mCurrentPosition;
        //当前视频如果为最后一个视频，则需要播放上一个视频
        if (tempCurrentPostion == list.size() - 1 && list.size() >= 2) {
            recycler.scrollToPosition(tempCurrentPostion - 1);
        }
        list.remove(tempCurrentPostion);
        adapter.notifyDataSetChanged();

    }

    /**
     * 视频列表获取失败
     */
    public void loadFailure() {
        if (refreshView.isRefreshing()) {
            refreshView.setRefreshing(false);
        }
    }

    /**
     * 获取当前播放的视频唯一标志
     */
    public String getCurrentUid() {
        String mCurrentUid = "";
        if (mListPlayer != null) {
            mCurrentUid = mListPlayer.getMediaInfo().getVideoId();
        }
        return mCurrentUid;
    }

    /**
     * 移动到指定的视频
     */
    public void moveTo(String uid, StsInfo stsInfo) {
        if (mListPlayer != null) {
//            mListPlayer.moveTo(uid,stsInfo);
        }
    }
}
